//
//  FKDownloadManager.m
//  FK
//
//  Created by handy wang on 6/8/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "FKDownloadManager.h"
#import "ASIHTTPRequestConfig.h"
#import "FKDownloadConfig.h"

@interface FKDownloadManager()

@property(nonatomic, retain, readwrite)NSMutableArray *downloadingTasks;
@property(nonatomic, retain, readwrite)ASIHTTPRequest *downloadingRequest;

- (void)performDelegateSelector:(SEL)selector withObject:(id)object1 withObject:(id)object2;

@end


@implementation FKDownloadManager

@synthesize downloadingTasks = _downloadingTasks;
@synthesize downloadingRequest = _downloadingRequest;

- (id)init {
    if (self = [super init]) {
        _delegates = [[NSMutableArray alloc] init];
        _downloadingTasks = [[NSMutableArray alloc] init];
    }
    return self;
}

+ (FKDownloadManager *)sharedInstance {
    static FKDownloadManager *_sharedInstance = nil;
    @synchronized(self) {
        if (!_sharedInstance) {
            _sharedInstance = [[FKDownloadManager alloc] init];
        }
    }
    return _sharedInstance;
}

- (void)startDownload {
    //TODO:网络不可用
    //    if () {
    //        return;
    //    }
    
    //无下载任务
    if ([FKDownloadManager sharedInstance].downloadingTasks.count <= 0) {
        [self performDelegateSelector:@selector(noTasksToDownload) withObject:nil withObject:nil];
        return;
    }
    
    NSURL *_requestURL = [NSURL URLWithString:((FKDownloadTask *)[_downloadingTasks objectAtIndex:0]).url];
    self.downloadingRequest = [ASIHTTPRequest requestWithURL:_requestURL];
    _downloadingRequest.username = nil;
    _downloadingRequest.password = nil;
    _downloadingRequest.delegate = self;
    _downloadingRequest.downloadProgressDelegate = self;
    _downloadingRequest.temporaryFileDownloadPath = [FKDownloadConfig temporaryFileDownloadPath];
    _downloadingRequest.temporaryUncompressedDataDownloadPath = [FKDownloadConfig temporaryUncompressedDataDownloadPath];
    _downloadingRequest.downloadDestinationPath = [FKDownloadConfig downloadDestinationPath];
    [_downloadingRequest startAsynchronous];
}

- (void)dealloc {
    self.downloadingTasks = nil;
    self.downloadingRequest = nil;
    [super dealloc];
}

#pragma mark - Public methods implementation

- (void)addDelegate:(id)delegateParam {
    if ((_delegates && [_delegates indexOfObject:delegateParam] == NSNotFound)) {
        [_delegates addObject:delegateParam];
    }
}

- (void)addANewTask:(FKDownloadTask *)aNewTask {
    if (_downloadingTasks && ([_downloadingTasks indexOfObject:aNewTask] == NSNotFound)) {
        [_downloadingTasks addObject:aNewTask];
    }
}

#pragma mark - Private methods implementation

- (void)performDelegateSelector:(SEL)selector withObject:(id)object1 withObject:(id)object2 {
    for (id _delegate in _delegates) {
        if ([_delegate respondsToSelector:selector]) {
            [_delegate performSelector:selector withObject:object1 withObject:object2];
        }
    }
}

#pragma mark - ASIHttpRequestDelegate

- (void)requestStarted:(ASIHTTPRequest *)request {

}

- (void)authenticationNeededForRequest:(ASIHTTPRequest *)request {
    
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    NSLog(@"INFO: Failed to download from %@ with comming message: %@", [request url], [[request error] localizedDescription]);
    FKDownloadTask *_failedDownloadingTask = [[_downloadingTasks objectAtIndex:0] retain];
    [_downloadingTasks removeObjectAtIndex:0];
    [self performDelegateSelector:@selector(requestFailed:withDownloadTask:) withObject:request withObject:_failedDownloadingTask];
    [_failedDownloadingTask release];
    _failedDownloadingTask = nil;
    if (_downloadingTasks.count > 0) {
        [self startDownload];
    } else {
        [self performDelegateSelector:@selector(didFinishAllTasksDownload) withObject:nil withObject:nil];
    }
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    FKDownloadTask *_succeedDownloadingTask = [[_downloadingTasks objectAtIndex:0] retain];
    [_downloadingTasks removeObjectAtIndex:0];
    [self performDelegateSelector:@selector(requestFinished:withDownloadTask:) withObject:request withObject:_succeedDownloadingTask];
    [_succeedDownloadingTask release];
    _succeedDownloadingTask = nil;
    if (_downloadingTasks.count > 0) {
        [self startDownload];
    } else {
        [self performDelegateSelector:@selector(didFinishAllTasksDownload) withObject:nil withObject:nil];
    }
}

@end